package com.media.photocamera.utils;

import android.app.Application;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.text.TextUtils;


import com.media.photocamera.imagelist.CameraImageBean;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by wisn on 2017/9/8.
 */

public class CameraFileUtils {
    /**
     * 复制文件并通知相册相关的应用更新db,否则文件保存成功，相册不能查看到
     *
     * @param context
     * @param oldFilePath
     * @param targetPathDir
     */
    public static void copyFile2Album(Application context, String oldFilePath, String targetPathDir) {
        ArrayList<CameraImageBean> list = new ArrayList<CameraImageBean>();
        list.add(new CameraImageBean(oldFilePath));
        copyFileList2Album(context, list, targetPathDir);
    }

    /**
     * 复制文件并通知相册相关的应用更新db,否则文件保存成功，相册不能查看到
     *
     * @param context
     * @param oldFileList
     * @param targetPathDir
     */
    public static void copyFileList2Album(Application context, List<CameraImageBean> oldFileList, String targetPathDir) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    File pRoot = new File(targetPathDir);
                    if (!pRoot.exists()) {
                        pRoot.mkdirs();
                    }
                    for (CameraImageBean imageBean : oldFileList) {
                        saveFileAndUpdateAlbum(imageBean.path, targetPathDir, context);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    private static void saveFileAndUpdateAlbum(String oldFilePath, String targetPathDir, Application context) {
        try {
            File oldFile = new File(oldFilePath);
            if (!oldFile.exists()) {
                return;
            }
            String mimeType = getImageTypeWithMime(oldFile.getAbsolutePath());
            String newFileName = System.currentTimeMillis() + "." + mimeType;
            String newPath = targetPathDir + newFileName;
            boolean result = copyFile(oldFile, new File(newPath));
            if (result) {
                //兼容华为不能扫描出来的情况 或者扫描出来两条记录的问题
                //  MediaStore.Images.Media.insertImage(context.getApplicationContext().getContentResolver(), newPath, name, "");
                context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse(newPath)));
                MediaScannerConnection.scanFile(context.getApplicationContext(),
                        new String[]{newPath},
                        new String[]{mimeType},
                        new MediaScannerConnection.OnScanCompletedListener() {
                            @Override
                            public void onScanCompleted(String path, Uri uri) {
                            }
                        });
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 批量删除缓存文件
     * @param context
     * @param oldFileList
     */
    public static void deleteCacheFileList(Application context, List<CameraImageBean> oldFileList) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    for (CameraImageBean imageBean : oldFileList) {
                        deleteCacheFile(context, imageBean.path);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    /**
     * 如果是缓存中的文件 会删除
     *
     * @param context
     * @param filepath
     */
    public static void deleteCacheFile(Application context, String filepath) {
        try {
            if (TextUtils.isEmpty(filepath) && !filepath.startsWith(getImageSaveRootPath(context))) {
                return;
            }
            File file = new File(filepath);
            if (file.exists()) {
                file.delete();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取指定的缓存根目录
     *
     * @param context
     * @return
     */
    public static String getImageSaveRootPath(Application context) {
        return context.getExternalCacheDir().getAbsolutePath() + File.separator;
//        return context.getCacheDir();
    }

    /**
     * 获取文件格式
     *
     * @param path
     * @return
     */
    public static String getImageTypeWithMime(String path) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(path, options);
        String type = options.outMimeType;
        // ”image/png”、”image/jpeg”、”image/gif”
        if (TextUtils.isEmpty(type)) {
            type = "";
        } else {
            type = type.substring(6);
        }
        return type;
    }

    /**
     * 格式化文件大小
     *
     * @param size
     * @return
     */
    public static String getReadableFileSize(long size) {
        if (size <= 0) {
            return "0";
        }
        final String[] units = new String[]{"B", "KB", "MB", "GB", "TB"};
        int digitGroups = (int) (Math.log10(size) / Math.log10(1024));
        return new DecimalFormat("#,##0.#").format(size / Math.pow(1024, digitGroups)) + " " + units[digitGroups];
    }


    /**
     * 拷贝单个文件到指定文件
     *
     * @param fromFile
     * @param toFile
     * @return
     */
    public static boolean copyFile(File fromFile, File toFile) {
        if (fromFile == null || toFile == null) {
            return false;
        }
        try {
            if (!toFile.exists()) {
                toFile.createNewFile();
            }
            return copyFileStream(new FileInputStream(fromFile), new FileOutputStream(toFile));
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }

    public static void savePictureByBitmap(String path, Bitmap bitmap) {
        File imgFile = new File(path);
        FileOutputStream fos = null;
        BufferedOutputStream bos = null;
        try {
            fos = new FileOutputStream(imgFile);
            bos = new BufferedOutputStream(fos);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
        } catch (Exception error) {
            error.printStackTrace();
        } finally {
            try {
                if (bos != null) {
                    bos.flush();
                    bos.close();
                }

                if (fos != null) {
                    fos.flush();
                    fos.close();
                }

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 拷贝流
     *
     * @param inputStream
     * @param outputStream
     * @return
     */
    public static boolean copyFileStream(InputStream inputStream, OutputStream outputStream) {
        try {
            int index = 0;
            byte[] bytes = new byte[1024];
            while ((index = inputStream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, index);
            }
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        } finally {
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    if (outputStream != null) {
                        outputStream.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return true;
    }


}
